//
//  MainViewController.swift
//  funcode
//
//  Created by Wan Jiading on 2017/6/6.
//  Copyright © 2017年 WanJiading. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

	var tabbarCenterView: MainTabbarCenterView!
	
    override func viewDidLoad() {
        super.viewDidLoad()

		// 设置 tabbarCenterView
		tabbarCenterView = MainTabbarCenterView(title: "磨耳朵", imageName: "radio_icon_normal", selectedImageName: "radio_icon_selected")
		self.tabBar.addSubview(tabbarCenterView)

		let screenSize = UIScreen.main.bounds.size
		let tabbarItemWidth: CGFloat = screenSize.width / CGFloat(viewControllers!.count)
		let tabbarItemHeight: CGFloat = 49 + 17
		let tabbarItemY: CGFloat = 49 - tabbarItemHeight
		let tabbarItemX: CGFloat = self.tabBar.centerX
		tabbarCenterView.snp.makeConstraints { (make) in
			make.centerX.equalTo(tabbarItemX)
			make.top.equalTo(tabbarItemY)
			make.width.equalTo(tabbarItemWidth)
			make.height.equalTo(tabbarItemHeight)
		}
		
		let tapGR = UITapGestureRecognizer(target: self, action: #selector(tapTabBarCenterView(_:)))
		tabbarCenterView.addGestureRecognizer(tapGR)
    }

	override func updateViewConstraints() {
		super.updateViewConstraints()
		
		self.tabBar.layoutIfNeeded()
	}
	
	
	func tapTabBarCenterView(_ gesture: UITapGestureRecognizer) {
		self.selectedIndex = self.viewControllers!.count / 2
		
		tabbarCenterView.setSelected(true)
	}
	
	
	override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
//		DebugLog(item.title)
		if (self.tabBar.items![2] != item) {
			tabbarCenterView.setSelected(false)
		}
	}
	
	
	override func awakeFromNib() {
		super.awakeFromNib()
		
		DebugLog(viewControllers)
		
		let centerIndex = viewControllers!.count / 2
		
		let centerItem = UITabBarItem(title: "", image: nil, tag: 0)
		
		let vc = UIViewController()
		let nav = UINavigationController(rootViewController: vc)
		vc.tabBarItem = centerItem
		
		viewControllers!.insert(nav, at: centerIndex)

	}
	
}
